#include <stdio.h>
#include <math.h>
#include <assert.h>

#define NPOWERSAMP 250
#define NPOWERSAMPBY2 125
#define NPOWERSAMPBY4 63

// 2pi/(NPOWERSAMP/3)
#define DPHI60 0.075398223686155036

unsigned short data[NPOWERSAMP] = {
    511,511,511,511,511,511,511,510,510,510,510,511,510,511,511,510,510,511,511,511,510,510,511,511,511,510,510,511,511,511,511,511,511,511,511,511,511,511,511,511,510,510,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,510,511,511,511,511,510,511,511,511,511,511,511,511,511,511,511,511,510,511,511,511,511,511,511,511,511,511,511,511,511,510,510,510,511,511,511,510,511,511,511,511,510,511,511,511,511,511,511,511,511,511,510,511,511,511,511,511,511,511,511,511,511,511,511,511,511,510,511,511,511,510,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,510,511,511,511,511,510,511,511,511,511,510,511,511,511,511,510,511,511,511,511,511,511,511,511,510,510,510,511,511,511,511,511,511,511,511,510,511,511,511,511,511,510,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,511,510,510,511,511,511,511,510,511,511,511,510,510,511,511,511,511,510,510,511,511,511,510,511,511,511,511,511,511,511,511,511,511,510,511,511,510,510
    };
unsigned char byteValue;
unsigned short uintValue;
float floatValue;

float cosk,sink;

unsigned char cycle;
float cosSum,sinSum,rmsCurrent;

void powerAnalysis() {
    cosSum = sinSum = 0;
    for(byteValue = 0; byteValue < NPOWERSAMPBY4; byteValue++) {
        if(byteValue == 0) {
            sink = 0;
            cosk = 1;
        }
        else {
            floatValue = DPHI60*byteValue;
            sink = sin(floatValue);
            cosk = cos(floatValue);
        }
        for(cycle = 0; cycle < 4; cycle++) {
            if((cycle%2) && (byteValue==0)) {
                cosk = -1;
                continue;
            }
            switch(cycle) {
                case 0:
                uintValue = data[byteValue];
                break;
                case 1:
                uintValue = data[NPOWERSAMPBY2-byteValue];
                cosk = -cosk;
                break;
                case 2:
                uintValue = data[NPOWERSAMPBY2+byteValue];
                sink = -sink;
                break;
                case 3:
                uintValue = data[NPOWERSAMP-byteValue];
                cosk = -cosk;
                break;
            }
            cosSum += uintValue*cosk;
            sinSum += uintValue*sink;
        }
    }
    // store the RMS current in cosSum
    rmsCurrent = 120*sqrt(cosSum*cosSum+sinSum*sinSum)/NPOWERSAMP;
}

void generate() {
    int k;
    double t;
    for(k = 0; k < NPOWERSAMP; k++) {
        t = DPHI60*k;
        data[k] = 511;//+100*(unsigned short)round(2*sin(t-0.5) + 0.5*sin(2*t-0.25) - 0.2*sin(2.5*t-0.5));
        //printf("%lf %d\n",t,data[k]);
    }
}

main() {
    //generate();
    powerAnalysis();
    printf("\n\n%f %f %f\n",cosSum,sinSum,rmsCurrent);
}